<template>
    <div class="demo-collapse" v-if="isWrite===false">

      <el-collapse v-model="activeName" accordion>
        <el-collapse-item v-for="item in items" :key="item.announcementid" :title="item.announcementtitle" :name="item.announcementid">
          <el-card>
            <div v-html="item.announcementcontent"/>
          </el-card>
          <p style="float:right; font-size: smaller;">发布日期：{{ item.announcementpublishTime }}</p>
        </el-collapse-item>
        <el-collapse-item :key="pageSize" title="广告" :name="-1">
          <div>    
            placeholder
          </div>
          <p style="float:right; font-size: smaller;">发布日期：now</p>
        </el-collapse-item>
      </el-collapse>
      <el-button type="primary" v-if="isAdmin" @click="isWrite=true">发布公告</el-button>
      <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 , 8 ,10, 15]"
                     layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
                     @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
    </div>

  <div style="border: 1px solid #ccc" v-if="isWrite">
    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
    />
    <el-form>
      <el-form-item label="标题">
        <el-input v-model="title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <Editor
          style="height: 500px; overflow-y: hidden;"
          v-model="valueHtml"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
      />
      <el-button type="primary" @click="addAnnouncement">提交</el-button>
      <el-button type="danger" @click="isWrite=false">取消</el-button>
    </el-form>
  </div>
</template>
  
<script lang="ts" setup>
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { AnnouncementListService ,AddAnnouncementService} from '@/api/annocement';
import useUserInfoStore from '@/stores/userInfo.js';
const activeName = ref(0)
const userInfoStore = useUserInfoStore();
const isAdmin=(userInfoStore.userInfo.usertype===1);
const isWrite=ref(false);

import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {IEditorConfig} from '@wangeditor/editor'
import request from '@/utils/request.js'
import { IDomEditor } from '@wangeditor/editor'
import {ElMessageBox,ElMessage} from "element-plus";
import router from '@/router/index.js';
const editorConfig: Partial<IEditorConfig> = {                     // JS 语法
        MENU_CONF: {},
        placeholder: '请输入内容...'
        // 其他属性...
    }
    
    // 修改 uploadImage 菜单配置
    editorConfig.MENU_CONF['uploadImage'] = {
        //server: '/api/upload-image',
        //fieldName: 'custom-field-name',
        // 继续写其他配置...
        async customUpload(file: File, insertFn: InsertFnType){            // JS 语法
            // file 即选中的文件
            // 自己实现上传，并得到图片 url alt href
            // 最后插入图片
            var form = new FormData()
            form.append('file',file)
            let result = request.post('/upload',form)
            let url = (await result).data
            let alt = "图片违规"
            let href = "https://gitee.com/D15771195036/upms/"
            insertFn(url, alt, href)
        }

        
        //【注意】不需要修改的不用写，wangEditor 会去 merge 当前其他配置
    }

  


    // 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

    // 内容 HTML
const valueHtml = ref('<p>hello</p>')
const title = ref('')



const toolbarConfig = {}

    // 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const addAnnouncement = async () =>{
  const newAnnouncementData=ref({
    announcementtitle: title.value,
    announcementcontent: valueHtml.value,
  })
  await AddAnnouncementService(newAnnouncementData.value)
  ElMessage.success('发布成功')
  isWrite.value=false;
  anno();
}





const items = ref([{
  announcementid:'',
  announcementtitle:'',
  announcementcontent:'',
  announcementpublishTime:''
},])

//const items = ref([])
//const message = ref('')

const pageNum = ref(+router.currentRoute.value.query.p)

const pageSize = ref(3)

const total = ref(0)
const onSizeChange = (size) => {
  pageSize.value = size
  anno();
}
//当前页码发生变化，调用此函数
const onCurrentChange = async (num) => {
  pageNum.value = num
  
  await router.push({path:'',query:{p:num}})
  anno();
}



const show = ref(false)
const anno = async () =>{
  let params ={
      pageNum: router.currentRoute.value.query.p,
      pageSize:pageSize.value
    }
    let result = await AnnouncementListService(params)
    items.value = result.data.items
    total.value = result.data.total
}
anno()


</script>

<style>
img:only-of-type{
    width: 500px;
    height: auto;
  }

</style>